#!/bin/bash
#author: <fanyuantao>
#date: 2024-08-08
#desc: This script is used to clena docker log files.

function clean_docker_log() {
    docker_container_logs=$(find /var/lib/docker/containers/ -name "*.log" -type f)
    echo "Start to clean log file ......"
    for log_file in $docker_container_logs; do
        echo ""
        container_id=$(basename $log_file | cut -d'-' -f1)
        container_name=$(docker ps -a -q --filter "id=$container_id" | xargs docker inspect --format '{{.Name}}' | cut -d'/' -f2)

        echo "Container : $container_name has log file size: $(du -h $log_file | cut -f1)"
        echo ""
        echo "Cleaning : $container_name"
        sleep 1
        truncate -s 0 $log_file
        echo "Clean : Done!"
    done
}

function echo_result() {
    echo "success"
}

function main() {
    clean_docker_log
    echo_result
}

main